// 工具函数模块

// 安全的localStorage操作
export function safeStorageGet(key) {
    try {
        return localStorage.getItem(key);
    } catch (error) {
        console.error('LocalStorage读取失败:', error);
        return null;
    }
}

export function safeStorageSet(key, value) {
    try {
        localStorage.setItem(key, value);
        return true;
    } catch (error) {
        console.error('LocalStorage写入失败:', error);
        // 注意：这里不应该直接调用showToast，因为这会导致循环依赖
        // showToast应该在UI层处理
        return false;
    }
}

// 防抖函数
export function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}

// 数据验证
export function validateUrl(url) {
    if (!url || typeof url !== 'string') return false;
    try {
        new URL(url);
        return true;
    } catch {
        return false;
    }
}

export function validateTabName(name) {
    if (!name || typeof name !== 'string') return false;
    name = name.trim();
    return name.length > 0 && name.length <= 20;
}

// 显示Toast提示
export function showToast(message, duration = 2000) {
    const toast = document.getElementById('toast');
    if (!toast) return;
    
    toast.textContent = message;
    toast.classList.add('opacity-100');
    
    setTimeout(() => {
        toast.classList.remove('opacity-100');
    }, duration);
}